//
//  BaseCheckOperator.m
//  Chamleon-template
//
//  Created by Fanty on 13-12-16.
//
//

#import "HttpCheckOperator.h"
#import "ChamleonHTTPRequest.h"

@implementation HttpCheckOperator

-(BOOL)checkResponseString:(ChamleonHTTPRequest*)request{
    
    _statusCode=[request responseStatusCode];
    _errorCode=0;
    if(request.error!=nil || _statusCode!=200){
        _errorCode=(int)request.error.code;
        _errorMessage=@"{\"success\":false,\"message\":\"网络异常\"}";
        if (_statusCode==520) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[request.responseString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            _errorMessage=[dict objectForKey:@"errorMsg"];
            
        }

        return NO;
    }
    else {
        NSData* data=[request responseData];
        
        if([data length]<2){
            _errorCode=900;
            _errorMessage=@"{\"success\":false,\"message\":\"网络异常\"}";
            return NO;
        }
        
        id jsonMap  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        
        if([jsonMap isKindOfClass:[NSDictionary class]]){
            NSDictionary* dict=(NSDictionary*)jsonMap;
            id resultObj=[dict objectForKey:@"success"];
            if(resultObj!=nil){
                BOOL ret=[resultObj boolValue];
                if(!ret){
                    _errorCode=1;
                    _errorMessage=[dict objectForKey:@"message"];
                }
            }
        }
        return (_errorCode==0);
    }
}

-(int)statusCode{
    return _statusCode;
}

-(int)errorCode{
    return _errorCode;
}

-(NSString*)errorMessage{
    if([_errorMessage length]<1)
        return @"网络异常";
    else
        return _errorMessage;
}


@end
